package org.leiyang.common.dfs;

import com.github.tobato.fastdfs.domain.fdfs.MetaData;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import io.netty.util.internal.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

@Service
public class FastDFSImpl implements OssOp {
    private static final Logger log = LoggerFactory.getLogger(FastDFSImpl.class);
    @Value("${dfs.url}")
    private String fastDfsUrl;
    private final FastFileStorageClient fastFileStorageClient;
    public FastDFSImpl(FastFileStorageClient fastFileStorageClient) {
        this.fastFileStorageClient = fastFileStorageClient;
    }

    @Override
    public String upload(InputStream fileInputStream, String fileOriginalFilename, Long fileSize) {
        if(fileSize == 0L)
            throw new RuntimeException("上传的图片文件为空");

        try {
            String fileExtName = "jpg";
            if(fileOriginalFilename.contains("."))
                fileExtName = fileOriginalFilename.substring(fileOriginalFilename.lastIndexOf(".") + 1);
            //设置元信息
            Set<MetaData> metaList = new HashSet<>(3);
            metaList.add(new MetaData("fileName", fileOriginalFilename));
            metaList.add(new MetaData("fileExtName", fileExtName));
            metaList.add(new MetaData("fileLength", String.valueOf(fileSize)));

            StorePath storePath = fastFileStorageClient.uploadFile(fileInputStream, fileSize, fileExtName, metaList);
            log.debug("上传图片完成，获得的StorePath : {}", storePath);
            if (Objects.nonNull(storePath)) {
                String baseUrl = fastDfsUrl.endsWith("/") ? fastDfsUrl : fastDfsUrl.concat("/");
                return baseUrl.concat(storePath.getFullPath());
            }
        } catch (Exception e) {
            log.error("图片文件上传失败，异常信息: ", e);
//            e.printStackTrace();
        }
        return "";
    }

    @Override
    public void deleteFile(String filePath) {
        if(StringUtil.isNullOrEmpty(filePath))
            return;
        //将绝对路径转化为{groupName/path}格式的相对路径
        if(filePath.startsWith("http")) {
            String baseUrl = fastDfsUrl.endsWith("/") ? fastDfsUrl : fastDfsUrl.concat("/");
            filePath = filePath.replace(baseUrl, "");
        }
        log.info("即将删除路径为: {}的FDFS上的文件.", filePath);
        fastFileStorageClient.deleteFile(filePath);
    }
}
